package com.kwamecorp.brunoperry.kwamelogo.engine;

import java.util.ArrayList;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.content.Context;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView.Renderer;
import android.opengl.Matrix;

public class KCRenderer implements Renderer
{
	private Context context;
	private KCListener listener;
	private ArrayList<KCModel3D> models;
	private ArrayList<KCCamera3D> cameras;

	private int numModels = 0;
	private int numCameras = 0;

	private int width;
	private int height;

	private float[] MVPMatrix = new float[16];

	private KCCamera3D currentCamera;

	public KCRenderer(Context context) {

		this.context = context;

		init();
	}

	private void init()
	{
		models = new ArrayList<KCModel3D>();
		cameras = new ArrayList<KCCamera3D>();
		cameras.add(new KCCamera3D());
		currentCamera = cameras.get(0);
		numCameras = cameras.size();
	}

	@Override
	public void onDrawFrame(GL10 arg0)
	{
		if (numModels == 0)
		{
			return;
		}

		// Set the viewport
		GLES20.glViewport(0, 0, width, height);
		GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
		GLES20.glClearColor(0.5f, 0.5f, 0.5f, 1.0f);

		update();
	}

	private void update()
	{
		currentCamera.update();

		for (int i = 0; i < numModels; i++)
		{
			KCModel3D model = models.get(i);
			Matrix.multiplyMM(MVPMatrix, 0, currentCamera.getViewMatrix(), 0, model.getModelMatrix(), 0);
			Matrix.multiplyMM(MVPMatrix, 0, currentCamera.getProjectionMatrix(), 0, MVPMatrix, 0);
			model.draw(MVPMatrix);
		}
	}

	@Override
	public void onSurfaceChanged(GL10 arg0, int width, int height)
	{
		this.width = width;
		this.height = height;

		float ratio = (float) this.width / this.height;

		currentCamera.init(ratio, -ratio, ratio, -1.0f, 1.0f, 1.0f, 2000.0f);
	}

	@Override
	public void onSurfaceCreated(GL10 arg0, EGLConfig arg1)
	{
		GLES20.glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
		GLES20.glEnable(GLES20.GL_CULL_FACE);
		GLES20.glEnable(GLES20.GL_DEPTH_TEST);

		listener.onSurfaceCreated();
	}

	public void addOnSurfaceCreatedListener(KCListener listener)
	{
		this.listener = listener;
	}

	public void addModel(KCModel3D model)
	{
		model.init();
		models.add(model);
		numModels = models.size();
	}

	public void addCamera(KCCamera3D camera)
	{
		cameras.add(camera);
		numCameras = cameras.size();
		currentCamera = camera;
		
	}

	public void setCurrentCamera(int cameraIndex)
	{
		currentCamera = cameras.get(cameraIndex);
	}
}
